'use strict';

module.exports = {
  up: async (queryInterface, Sequelize) => {
    await queryInterface.createTable('ai_analysis_cache', {
      id: {
        allowNull: false,
        autoIncrement: true,
        primaryKey: true,
        type: Sequelize.INTEGER
      },
      user_id: {
        type: Sequelize.INTEGER,
        allowNull: false,
        references: {
          model: 'users',
          key: 'id'
        },
        onUpdate: 'CASCADE',
        onDelete: 'CASCADE'
      },
      request_hash: {
        type: Sequelize.STRING(64),
        allowNull: false,
        comment: '请求参数的哈希值，用于判断是否需要重新分析'
      },
      clothing_count: {
        type: Sequelize.INTEGER,
        allowNull: false,
        comment: '分析时的衣服数量'
      },
      weather_info: {
        type: Sequelize.JSON,
        allowNull: true,
        comment: '天气信息'
      },
      ai_provider: {
        type: Sequelize.STRING(50),
        allowNull: false,
        comment: 'AI提供商：doubao, deepseek, qianwen等'
      },
      ai_model: {
        type: Sequelize.STRING(100),
        allowNull: true,
        comment: 'AI模型名称'
      },
      ai_analysis: {
        type: Sequelize.TEXT('long'),
        allowNull: false,
        comment: 'AI原始分析结果'
      },
      recommendations: {
        type: Sequelize.JSON,
        allowNull: false,
        comment: '生成的搭配推荐'
      },
      token_usage: {
        type: Sequelize.JSON,
        allowNull: true,
        comment: 'Token使用情况'
      },
      response_time: {
        type: Sequelize.INTEGER,
        allowNull: true,
        comment: 'AI响应时间（毫秒）'
      },
      is_valid: {
        type: Sequelize.BOOLEAN,
        allowNull: false,
        defaultValue: true,
        comment: '缓存是否有效'
      },
      created_at: {
        allowNull: false,
        type: Sequelize.DATE,
        defaultValue: Sequelize.literal('CURRENT_TIMESTAMP')
      },
      updated_at: {
        allowNull: false,
        type: Sequelize.DATE,
        defaultValue: Sequelize.literal('CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP')
      }
    });

    // 添加索引
    await queryInterface.addIndex('ai_analysis_cache', ['user_id']);
    await queryInterface.addIndex('ai_analysis_cache', ['request_hash']);
    await queryInterface.addIndex('ai_analysis_cache', ['user_id', 'request_hash'], {
      unique: true
    });
    await queryInterface.addIndex('ai_analysis_cache', ['created_at']);
  },

  down: async (queryInterface, Sequelize) => {
    await queryInterface.dropTable('ai_analysis_cache');
  }
};
